<?php

namespace app\common\service\auth;

use app\model\AgentChannel;
use app\model\MobileUser;
use think\Exception;

class AuthPubService extends AuthBase implements AuthInterface
{
    /**
     * @var MobileUser $user
     */
    public $user;

    /**
     * @var AgentChannel $agentChannel
     */
    public $agentChannel;

    /**
     * @var array $params
     */
    public  $params =[];

    public function attempt($params)
    {
        if (empty($params['conversion_url']) || empty($params['partner_id'])) {
            throw new Exception('缺少必要参数');
        }

        $urlQuery = html_entity_decode(parse_url($params['conversion_url'])['query']);
        parse_str($urlQuery, $param);

        request()->setParam($param);

        if (empty($param['channel'])) {
            throw new Exception('渠道不存在');
        }

        $this->agentChannel = AgentChannel::query()->cache('AuthPubService' . $param['channel'], 3600)->where('name', $param['channel'])->find();

        if (empty($this->agentChannel)) {
            throw new Exception('渠道不存在');
        }

        $mobileUser = MobileUser::query()
//            ->cache('mobileUser'.$this->agentChannel->agent_id.$params['partner_id'],3600)
            ->where('agent_id',$this->agentChannel->agent_id)
            ->where('openid',$params['partner_id'])
            ->where('app_id','pub')
            ->find();

        if (empty($mobileUser)){
            $mobileUser = MobileUser::findOrCreate([
                'app_id' => 'pub',
                'agent_id' => $this->agentChannel->agent_id,
                'openid' => $params['partner_id'],
                'token' => (microtime(true)*10000).rand(1,999999999999)
            ]);
        }

        $this->user = $mobileUser;

        return true;


    }

    public function login($params)
    {
        // TODO: Implement login() method.
    }

    public function id()
    {
        return $this->user->id;
    }

    /**
     * @return MobileUser
     */
    public function user()
    {
        return $this->user;
    }

    public function channelId()
    {
        // 如果这边报错检查是否实例化 Auth::attemptChannel()

        return $this->agentChannel->id;
    }

    public function agentId()
    {
        // 如果这边报错检查是否实例化 Auth::attemptChannel()
        return $this->agentChannel->agent_id;
    }




}